import random
from pymongo import MongoClient  

# 连接到MongoDB（确保MongoDB服务已在本地运行）  
client = MongoClient("mongodb://192.168.168.110:27017/")  

# 选择数据库  
db = client['data']  

# 获取玩家的用户名
users = db.user.find({}, {"name": 1})  # 查询所有用户的名字
player_names = [user['name'] for user in users]  # 提取名字到列表

# 确保有足够的玩家
if len(player_names) < 4:
    print("用户数量不足，至少需要 4 个用户。")
    client.close()
    exit()

# 定义牌
cards = ['A'] * 6 + ['K'] * 6 + ['Q'] * 6 + ['大王', '小王']

# 随机洗牌
random.shuffle(cards)

# 初始化玩家
players = {player_names[i]: [] for i in range(4)}  # 使用从数据库获取的用户名

# 发牌
for _ in range(5):  # 每人发5张
    for player in players:
        players[player].append(cards.pop())

# 打印每个玩家的牌并插入数据库
for player, hand in players.items():
    for card in hand:  # 遍历玩家的每张牌
        usercard_data = {  
            "username": player,  
            "card": card  # 插入单张牌
        }  
        # 插入文档到 usercard 集合  
        db.usercard.insert_one(usercard_data)  

    # 验证插入的数据  
    # print(f"Usercards for {player}:")  
    # for entry in db.usercard.find({"username": player}):  
    #     print("登录平台")  

# 关闭MongoDB连接  
client.close()
